import * as React from "react";
import { observer } from "mobx-react";
import { observable } from "mobx";
import {
  Row,
  Col,
  Button,
  Table,
  Modal,
  Form,
  Input,
  // Select,
  Typography,
  Space,
  Spin,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import IconFont from "../../../../../../assets/ICON";
import "./index.less";
import TreeTransfer from "../TreeTransfer";
import {
  AddRole,
  getfindAllRole,
  EditRole,
  getfindAllMenu,
  BindRoleMenu,
  getRoleMenus,
} from "../../../ServeApi";
import { AjaxData } from "../../../../../../data/interface/publicInterface";
// const { Option } = Select;
const { Text } = Typography;
export interface MenuTableProps {}

export interface MenuTableState {}

interface columnsDataCLass {
  title: string;
  dataIndex: string;
  render?: any;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
    md: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
    md: { span: 16 },
  },
};
@observer
class MenuTable extends React.Component<MenuTableProps, MenuTableState> {
  @observable private columns: columnsDataCLass[] = [
    {
      title: "名称",
      dataIndex: "name",
    },
    {
      title: "主页路径",
      dataIndex: "indexUrl",
    },
    {
      title: "创建日期 ",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      dataIndex: "isDefault",
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ color: "#595959" }}
                onClick={() => {
                  this.onEdit(record);
                }}
              >
                <IconFont
                  type="icon_form_bianji"
                  style={{ color: "#FBB10B" }}
                />
                <Text>编辑</Text>
              </span>
              {text === "1" ? null : (
                <span
                  onClick={() => {
                    this.onAuthorize(record);
                  }}
                >
                  <IconFont
                    type="icon_form_shouquan2"
                    style={{ color: "#43D80F" }}
                  />
                  <Text>授权</Text>
                </span>
              )}

              <span
              // onClick={() => {
              //   this.onDelete(record);
              // }}
              >
                <IconFont
                  type="icon_form_shanchu"
                  style={{ color: "#FF6B6B" }}
                />
                <Text>删除</Text>
              </span>
            </Space>
          </>
        );
      },
    },
  ];
  @observable protected TableData = [];
  @observable private isModalVisible: boolean = false;
  @observable private isModalMenuwarrant: boolean = false;
  private initValue: any = null; //编辑信息副本
  private initAuthorizeValue: any = null; //编辑授权信息副本

  private Mod: string = "add";
  private instance: any = null;
  private dataList: any[] = []; //平面结构完整菜单
  private defaultTransferValue: any[] = []; //编辑授权值
  private transferValue: any[] = []; //编辑授权值
  state = {
    loading: false,
  };
  render() {
    return (
      <>
        <div className="rowcon_body">
          <div>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                this.addMenuModal();
              }}
            >
              新增
            </Button>
          </div>
          <div className="rowcon_bottom"></div>
          <Spin spinning={this.state.loading}>
            <Table columns={this.columns} dataSource={this.TableData}></Table>
          </Spin>
          <Modal
            title={this.Mod === "add" ? "新增角色" : "编辑角色"}
            visible={this.isModalVisible}
            onOk={() => {
              this.handleOk();
            }}
            onCancel={() => {
              this.handleCancel();
            }}
          >
            <Form {...formItemLayout} ref={(el) => (this.instance = el)}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label="角色名称："
                    name="name"
                    rules={[
                      {
                        required: true,
                        message: "请填写角色名称",
                      },
                    ]}
                  >
                    <Input placeholder="请填写角色名称" />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item label="主页路径：" name="indexUrl">
                    <Input placeholder="主页路径" />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Modal>
          <Modal
            title="角色授权"
            visible={this.isModalMenuwarrant}
            onOk={() => {
              this.AuthorizeOk();
            }}
            onCancel={() => {
              this.AuthorizeCancel();
            }}
          >
            <TreeTransfer
              dataSource={this.dataList}
              onRight={(arr: any[]) => {
                this.canbacksetTransfer(arr);
              }}
              defaultValue={this.defaultTransferValue}
            />
          </Modal>
        </div>
      </>
    );
  }
  /**
   * 钩子函数
   */
  componentWillMount() {
    this.init();
  }

  /**
   * 请求接口
   */
  getMenuList() {
    getfindAllMenu().then((rnt) => {
      if (rnt) {
        let Json = rnt.json();
        Json.then((res: AjaxData) => {
          if (res.success) {
            let map = res.data.map((item) => {
              let dd = {
                key: item.treeId,
                title: item.name,
                parentkey: item.parentId,
                disabled: false,
              };
              return dd;
            });
            this.dataList = map; //菜单平面数据
            // this.treeLeftData = this.listToTree(map); //菜单树状数据
            this.forceUpdate();
          } else {
            Modal.error({ title: res.message });
          }
        });
      }
    });
  }
  async getData() {
    let _this = this;
    this.setState({ loading: true });
    let res = await getfindAllRole().catch((err) => {
      console.log(err);
      _this.setState({ loading: false });
    });
    if (res) {
      let Json = res.json();
      Json.then((data: AjaxData) => {
        if (data.success) {
          this.TableData = data.data;
          this.setState({ loading: false });
          this.forceUpdate();
        } else {
          Modal.error({
            title: data.message,
            onOk: () => {
              _this.setState({ loading: false });
            },
          });
        }
      });
    }
  }
  //修改或者新增
  setData(item: any) {
    let _this = this;
    for (let key in item) {
      item[key] = item[key] ? item[key] : null;
    }
    switch (this.Mod) {
      case "add":
        this.setState({ loading: true });
        AddRole(JSON.stringify(item))
          .then((rnt) => {
            if (rnt) {
              let Json = rnt.json();
              Json.then((res: AjaxData) => {
                if (res.success) {
                  this.setState({ loading: false });
                  this.init();
                } else {
                  Modal.error({
                    title: res.message,
                    onOk: () => {
                      _this.setState({ loading: false });
                    },
                  });
                }
              });
            }
          })
          .catch((err) => {
            this.setState({ loading: false });
          });
        break;
      case "updata":
        item["id"] = this.initValue["id"];
        this.setState({ loading: true });
        EditRole(JSON.stringify(item))
          .then((rnt) => {
            if (rnt) {
              let Json = rnt.json();
              Json.then((res: AjaxData) => {
                if (res.success) {
                  this.setState({ loading: false });
                  this.init();
                } else {
                  Modal.error({
                    title: res.message,
                    onOk: () => {
                      _this.setState({ loading: false });
                    },
                  });
                }
              });
            }
          })
          .catch((err) => {});
        break;
      default:
        break;
    }
  }
  /**
   *  操作函数
   */
  //初始化
  init() {
    this.getData();
    this.getMenuList();
  }
  //点击授权
  onAuthorize(item) {
    this.ifMenuwarrant();
    this.initAuthorizeValue = item;
    let pream = {
      roleId: this.initAuthorizeValue.id,
    };
    getRoleMenus(JSON.stringify(pream))
      .then((rnt) => {
        if (rnt) {
          let Json = rnt.json();
          Json.then((res: AjaxData) => {
            if (res.success) {
              this.defaultTransferValue = res.data;
              this.forceUpdate();
            } else {
              Modal.error({ title: res.message });
            }
          });
        }
      })
      .catch((err) => {});
  }
  canbacksetTransfer(arr: any) {
    // console.log(arr);
    this.transferValue = arr;
  }
  ifMenuwarrant() {
    this.isModalMenuwarrant = !this.isModalMenuwarrant;
    this.forceUpdate();
  }
  AuthorizeOk() {
    this.ifMenuwarrant();
    let pream = {
      roleId: this.initAuthorizeValue.id,
      menuIdList: this.transferValue,
    };
    BindRoleMenu(JSON.stringify(pream))
      .then((rnt) => {
        if (rnt) {
          let Json = rnt.json();
          Json.then((res: AjaxData) => {
            if (res.success) {
            } else {
              Modal.error({ title: res.message });
            }
          });
        }
      })
      .catch((err) => {});
  }
  AuthorizeCancel() {
    this.ifMenuwarrant();
  }
  //编辑操作
  onEdit(item) {
    this.initValue = item;
    this.Mod = "updata";
    this.ifVisible();
    setTimeout(() => {
      if (this.instance) {
        const container: any = (this.instance as any) as HTMLDivElement;
        container.setFieldsValue(item);
      }
    });
  }
  //新增角色对话框
  addMenuModal() {
    this.Mod = "add";
    this.ifVisible();
  }
  //新增编辑弹窗开启或关闭
  ifVisible() {
    this.isModalVisible = !this.isModalVisible;
    this.forceUpdate();
  }
  //新增编辑弹窗确认
  handleOk() {
    // this.ifVisible();
    let _this = this;

    const container: any = (this.instance as any) as HTMLDivElement;
    container
      .validateFields()
      .then((res) => {
        console.log(res);
        _this.setData(res);
        _this.ifVisible();
        _this.clearFromData();
      })
      .catch((err) => {
        console.log(err);
      });
  }
  //新增编辑弹窗取消
  handleCancel() {
    this.ifVisible();
  }
  //清空From表单
  clearFromData() {
    if (this.instance) {
      const container: any = (this.instance as any) as HTMLDivElement;
      container.setFieldsValue({
        name: undefined,
        indexUrl: undefined,
      });
    }
  }
}

export default MenuTable;
